package cn.swust.designpatternlearningplatform.common.utils;

import cn.swust.designpatternlearningplatform.domain.bo.TokenInfoBo;
import com.alibaba.druid.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    // TOKEN的有效期10小时（S）
    private static final int TOKEN_TIME_OUT = 3600*24;

    // 加密KEY
    private static final String TOKEN_SECRET = "dpacr";


    public static String NAME = "name";
    public static String NUMBER = "number";
    public static String ROLE = "role";


    // 生成Token
    public static String getToken(Map<String,Object> params){
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, TOKEN_SECRET) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
                .addClaims(params)
                .compact();
    }

    /**
     * 根据用户信息生成token
     */
    public static String getToken(TokenInfoBo tokenInfoBo){
        Map<String, Object> params = new HashMap<>();
        params.put(NAME,tokenInfoBo.getName());
        params.put(NUMBER,tokenInfoBo.getNumber());
        params.put(ROLE,tokenInfoBo.getRole());
        return getToken(params);
    }


    /**
     * 从token中获取用户信息
     */
    public static TokenInfoBo parseToken(String token){
        return getInfoByClaims(getClaims(token));
    }

    /**
     * 获取Token中的claims信息
     * 目前看来只需要保存 id，number，name，role即可
     */
    public static Claims getClaims(String token) {
        return Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(token).getBody();
    }

    /**
     * 从claims中解析出用户信息
     */
    private static TokenInfoBo getInfoByClaims(Claims claims){
        TokenInfoBo tokenInfoBo = new TokenInfoBo();
        tokenInfoBo.setName(claims.get(NAME,String.class));
        tokenInfoBo.setNumber(claims.get(NUMBER,String.class));
        tokenInfoBo.setRole(claims.get(ROLE,String.class));
        return tokenInfoBo;
    }

    /**
     * 是否有效 true-有效，false-失效
     */
    public static boolean verifyToken(String token) {

        if(StringUtils.isEmpty(token)) {
            return false;
        }

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("dpacr")
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e) {
            return false;
        }
        return true;
    }
}
